import { useProjectStore } from "@/store/projectStore";
import { Button, Space, Table } from 'antd'
import type { Project } from "@/types/projectTypes";
import type { ColumnsType, TablePaginationConfig } from "antd/es/table";
import { useCallback } from "react";
import { useBranchStore } from "@/store/branchStore";

type TableData = Project & { key: number, branches: string[] };
export default function Home() {
    const { projects, pageInfo, loadProjects } = useProjectStore();
    const { branchsDict, loadBranches } = useBranchStore();
    const data = projects.map(p => ({ ...p, key: p.id, branches: branchsDict[p.id]?.map(b => b.name) || [] })) as TableData[];
    const tableColumns: ColumnsType<TableData> = [
        { key: "id", title: "ID", dataIndex: "id", width: 50 },
        { key: "name", title: "Name", dataIndex: "name", width: 180 },
        { key: "web_url", title: "Web URL", dataIndex: "web_url", width: 500 },
        { key: "branches", title: "Branches", dataIndex: "branches", width: 200 },
        {
            title: 'Action',
            key: 'action',
            render: (_, record) => (
                <Space size="middle">
                    <Button onClick={() => loadBranches(record.id)}>加载分支</Button>
                </Space>
            ),
        },
    ];
    const pagination = { ...pageInfo, showSizeChanger: true, showTotal: (total: number) => `Total ${total} items` };
    const handleButtonClick = useCallback(() => {
        loadProjects(1, 20);
    }, [loadProjects]);
    const handleTableChange = useCallback(({ current, pageSize }: TablePaginationConfig) => {
        loadProjects(current ?? 1, pageSize ?? 20);
    }, [loadProjects]);
    const handleLoadAllBranches = useCallback(() => {
        projects.forEach(p => loadBranches(p.id));
    }, [loadBranches, projects]);
    return (
        <div>
            <h1>仓库</h1>
            <Button type="primary" onClick={handleButtonClick}>查询仓库</Button>&nbsp;
            <Button type="primary" onClick={handleLoadAllBranches}>加载全部分支</Button>
            <Table<TableData> dataSource={data} columns={tableColumns} pagination={pagination} onChange={handleTableChange} />
        </div>
    )
}
